package core.cards.election.model;

public class ElectionResultSubBackend {
	private String rkwName;
	private int votersCount;
	private int maxVotersCount;

	private ElectionBackend voteResult;

	public ElectionResultSubBackend(String rkwName, ElectionBackend votingCard) {
		this.rkwName = rkwName;
		votersCount = 0;
		maxVotersCount = 0;

		voteResult = initVoteResult(votingCard);
	}
	
	public void setMaxVotersCount(int maxVotersCount) {
		this.maxVotersCount = maxVotersCount;
	}

	public void increaseVotersCount(int votersCount) {
		this.votersCount += votersCount;
	}

	private ElectionBackend initVoteResult(ElectionBackend electionBackend) {
		ElectionBackend newElectionBackend = new ElectionBackend();
		for (VotingCard votingCard : electionBackend.getVotingCardList()) {
			VotingCard newVotingCard = new VotingCard(newElectionBackend);
			newVotingCard.setName(votingCard.getName());
			newVotingCard.setDescription(votingCard.getDescription());
			newVotingCard.setChecksAllowed(votingCard.getChecksAllowed());
			for (VotingCardOption votingCardOption : votingCard.getVotingCardOptionList()) {
				VotingCardOption newVotingCardOption = new VotingCardOption(newVotingCard);
				newVotingCardOption.setName(votingCardOption.getName());
				newVotingCard.addVotingCardOption(newVotingCardOption);
			}
			newElectionBackend.addVotingCard(newVotingCard);
		}
		return newElectionBackend;
	}

	public void addVote(ElectionBackend vote) {
		for (int i = 0; i < vote.getVotingCardList().size(); i++) {
			VotingCard voteCard = vote.getVotingCardList().get(i);
			VotingCard resultCard = voteResult.getVotingCardList().get(i);

			if (voteCard.isValid()) {
				for (int j = 0; j < voteCard.getVotingCardOptionList().size(); j++) {
					VotingCardOption voteCardOption = voteCard.getVotingCardOptionList().get(j);
					VotingCardOption resultCardOption = resultCard.getVotingCardOptionList().get(j);
					if (voteCardOption.isChecked()) {
						resultCardOption.incValue();
					}
				}
			}
		}
	}

	public String getName() {
		return rkwName;
	}
	
	public ElectionBackend getVoteResult() {
		return voteResult;
	}

	@Override
	public String toString() {
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.append("==========\n");
		stringBuilder.append("*name: ").append(rkwName).append("\n").append(voteResult).append("\n");
		stringBuilder.append(votersCount).append("/").append(maxVotersCount);
		return stringBuilder.toString();
	}
}